from django.shortcuts import render
from rest_framework.views import APIView
from celery_tasks.sms_code.tasks import send_sms_code
from rest_framework.response import Response
from yunfei.serializers import *
import random
import redis
from yunfei.models import *
# 短信验证码
class Sms_codeView(APIView):
	def get(self,request):
		mobile = request.query_params.get('phone')
		data = random.randint(1000,9999)
		if mobile:
			resp = send_sms_code.delay(mobile,data)
			print('异步验证码>>>',resp)
			if resp:
				rdc = redis.Redis()
				rdc.setex('sms_%s' % mobile,600,data)
				print('>>>',data)
				return Response({'code':200,'msg':data})
			else:
				return Response({'code':500,'msg':'发送失败'})
		else:
			return Response({'code':400,'msg':'参数错误'})
# 登录
class LoginView(APIView):
	def get(self,request):
		mobile = request.data.get('phone')
		sms_code = request.data.get('sms_code')
		print('验证码>>>',sms_code)
		rdc = redis.Redis()
		real_sms_code = rdc.get('sms_%s' % mobile)
		if not real_sms_code:
			return Response({'code':500,'msg':'验证码不存在或过期'})
		if real_sms_code.decode() != sms_code:
			return Response({'code':500,'msg':'验证码错误'})
		# 判断是否第一次登录
		try:
			user = User_mobile.objects.get(mobile=mobile)
			return Response({'code':200,'msg':'登录成功'})
		except Exception as e:
			try:
				user_info = User_mobile.objects.create(mobile=mobile)
				return Response({'code':201,'msg':'注册并登录成功'})
			except Exception as e:
				return Response({'code':500,'msg':'服务器错误'})

